import { trim, isEmpty } from 'lodash';
import { Op } from 'sequelize';
import BaseController from './base';
import HotelModel from '../models/hotel';
import { stars, starMap } from '../values';
import States from '../models/state';
import superagent from 'superagent';
import WeixinAccessTokenModel from '../models/weixin-access-token';

// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class HotelController extends BaseController {
  getModel() {
    return HotelModel;
  }

  getAttributes() {
    return { attributes: { exclude: ['appsecret'] } };
  }

  getFindWhere(req) {
    const { code, name } = req.query;
    const where = {};
    if (trim(code)) {
      where.code = { [Op.like]: `%${trim(code)}%` };
    }

    if (trim(name)) {
      where.name = { [Op.like]: `%${trim(name)}%` };
    }

    return { where: isEmpty(where) ? undefined : where };
  }

  getInclude(req) {
    return {
      include: [{
        model: States,
        as: 'state'
      }]
    };
  }

  async generateUrllink(req, res, next) {
    try {
      const { hotel_id } = req.user;
      const { confirmNumber } = req.params;

      const hotel = await HotelModel.findById(hotel_id);
      const weixinAccessToken = await WeixinAccessTokenModel.findOne({
        where: {
          hotel_id: hotel.id,
          appid: hotel.appid
        },
        rejectOnEmpty: new Error('未找到微信访问凭证')
      });

      const response = await superagent
        .post(`https://api.weixin.qq.com/wxa/generate_urllink?access_token=${weixinAccessToken.access_token}`)
        .set('Content-Type', 'application/json')
        .accept('application/json')
        .send({
          query: JSON.stringify({ confirmNumber }),
          expire_type: 1,
          expire_interval: 10,
          env_version: 'develop',
        });

      if (response.status === 200) {
        console.log('https://api.weixin.qq.com/wxa/generate_urllink', 'res.body', response.body);
        if (response.body) {
          console.log(response.body);
        }
      }

      res.sendOk();
    } catch (e) {
      next(e);
    }
  }
}

export default new HotelController();
